import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI, getUserProfileAPI, getUserPhotoAPI } from '@/api'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}
const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, newToken) => {
    state.token = newToken
    setToken(newToken)
  },
  REMOVE_TOKEN: (state, token) => {
    state.token = ''
    removeToken()
  },
  SET_USERINFO: (state, value) => {
    state.userInfo = value
  },
  REMOVE_USERINFO: () => {
    state.userInfo = {}
  }
}

const actions = {
  // 进行异步操作
  // 封装登录的接口
  async loginActions({ commit }, value) {
    const [err, res] = await loginAPI(value)
    if (!err) commit('SET_TOKEN', res.data)
    return [err, res]
  },
  // 封装用户信息的接口
  async getUserInfoActions({ commit }) {
    const res = await getUserProfileAPI()
    const user = await getUserPhotoAPI(res.data.userId)
    console.log(res)
    commit('SET_USERINFO', { ...res.data, ...user.data })
  },
  // 退出登录
  logOutActions({ commit }) {
    // 删除vuex和本地token
    // 先清除本地的token,再重置state
    commit('REMOVE_TOKEN')
    commit('REMOVE_USERINFO')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
